#include <iostream>
#include <queue>
#define int long long
using namespace std;

struct a{
	int num;
	bool operator < (const a x)const{
		return num>x.num;
	}
};


signed main(){
	priority_queue<a> q;
	int n;
	cin>>n;
	int ans=0;
	for(int i=0;i<n;i++){
		a x;
		cin>>x.num;
		q.push(x);
		if(q.top().num < x.num){
			ans += x.num-q.top().num;
			q.pop();
			q.push(x);
		}
	}
	cout<<ans;
	return 0;
}
